package com.sxtyxt.online.me;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.sxtyxt.entity.ResultVo;
import com.sxtyxt.entity.User;
import com.sxtyxt.online.ActBase;
import com.sxtyxt.online.ActLogin;
import com.sxtyxt.online.ActWeb;
import com.sxtyxt.online.App;
import com.sxtyxt.online.AppManager;
import com.sxtyxt.online.R;
import com.sxtyxt.online.SystemConst;
import com.sxtyxt.online.SystemEnv;
import com.sxtyxt.online.file.ActAddFileDetail;
import com.sxtyxt.online.imagecrop.ActClipImage;
import com.sxtyxt.util.DataCleanManager;
import com.sxtyxt.util.DialogUtil;
import com.sxtyxt.util.FileUtil;
import com.sxtyxt.util.GsonUtil;
import com.sxtyxt.util.IconSelectWindow;
import com.sxtyxt.util.ImageLoaderUtil;
import com.sxtyxt.util.ImageUtil;
import com.sxtyxt.util.ToastUtil;
import com.sxtyxt.volley.LoadingDialogResultListenerImpl;
import com.sxtyxt.volley.ResultListenerImpl;
import com.sxtyxt.volley.URL;
import com.sxtyxt.volley.VolleyUtils;
import com.sxtyxt.widget.ActionSheetDialog;

import org.hybridsquad.android.library.CropHandler;
import org.hybridsquad.android.library.CropHelper;
import org.hybridsquad.android.library.CropParams;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/6.
 */

public class ActMe extends ActBase implements View.OnClickListener {

    private TextView txtName;               //用户名

    private ImageView ivHeader;             //用户头像
    private ImageView ivNotLogin;           //用户未登陆头像
    private ScrollView scrollView;
    private View view;
    private TextView txtSetPhoto;
    private LinearLayout layoutPersonalInfo;
    private String uploadPath;
    private LinearLayout layoutModifyPassword;
    private LinearLayout layoutAbout;
    private TextView txtChoosePhoto;
    private IconSelectWindow mSelectWindow;
    @Override
    protected int getLayoutId() {
        return R.layout.me;
    }

    @Override
    protected void initUI() {
        super.initUI();

        txtName = (TextView) findViewById(R.id.txt_name);
//        头像
        ivNotLogin = (ImageView) findViewById(R.id.iv_not_login);
        ivNotLogin.setOnClickListener(this);
        txtChoosePhoto = (TextView) findViewById(R.id.txt_choosePhoto);
        txtChoosePhoto.setOnClickListener(this);
        //        个人中心
        layoutPersonalInfo= (LinearLayout) findViewById(R.id.layout_Personalinformation);
        layoutPersonalInfo.setOnClickListener(this);

        //密码修改
        layoutModifyPassword = (LinearLayout) findViewById(R.id.layout_myinfoPassword);
        layoutModifyPassword.setOnClickListener(this);
        //关于我们
        layoutAbout = (LinearLayout) findViewById(R.id.layout_about);
        layoutAbout.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.layout_Personalinformation:
                transfer(ActMyInfo.class);
                break;
            case R.id.txt_choosePhoto:
                if (mSelectWindow==null){
                    mSelectWindow = new IconSelectWindow(this,mListener);
                }
                if (mSelectWindow.isShowing()){
                    mSelectWindow.dismiss();
                    return;
                }
                mSelectWindow.show();
                break;
            case R.id.layout_myinfoPassword:
                transfer(ActModifyPwd.class);
                break;

            case R.id.layout_about:
                Intent intent = new Intent(this, ActAbout.class);
                startActivity(intent);
                break;


            default:
                break;
        }
    }
    // 跳转的监听
    private IconSelectWindow.Listener mListener = new IconSelectWindow.Listener() {
        // 到相册
        @Override
        public void toGallery() {
            // 清除缓存
            CropHelper.clearCachedCropFile(mCropHandler.getCropParams().uri);

            Intent intent = CropHelper.buildCropFromGalleryIntent(mCropHandler.getCropParams());
            startActivityForResult(intent, CropHelper.REQUEST_CROP);
        }

        // 到相机
        @Override
        public void toCamera() {
            // 清除之前剪切的图片的缓存
            CropHelper.clearCachedCropFile(mCropHandler.getCropParams().uri);

            // 跳转
            Intent intent = CropHelper.buildCaptureIntent(mCropHandler.getCropParams().uri);
            startActivityForResult(intent, CropHelper.REQUEST_CAMERA);
        }
    };
    // 图片处理
    private CropHandler mCropHandler = new CropHandler() {
        // 图片剪切之后：参数Uri代表剪切后的图片
        @Override
        public void onPhotoCropped(Uri uri) {
            // 拿到剪切之后的图片
            File file = new File(uri.getPath());
            // TODO: 2017/6/8 进行网络请求将图片上传
//            头像上传

            List<File> files = new ArrayList<File>();
            files.add(file);
            List<String> filePartNames = new ArrayList<String>();
            filePartNames.add("userimg");
            pictureUpload(files,filePartNames);
        }

        // 取消
        @Override
        public void onCropCancel() {
            doToast("剪切取消");
        }

        // 剪切失败
        @Override
        public void onCropFailed(String message) {
            doToast(message);
        }

        // 剪切的参数设置：Uri(图片剪切之后保存的路径)
        @Override
        public CropParams getCropParams() {
            // 默认的剪切设置
            CropParams cropParams = new CropParams();
            return cropParams;
        }

        // 上下文
        @Override
        public Activity getContext() {
            return ActMe.this;
        }
    };
    //            头像上传
    private void pictureUpload(List<File> files,List<String> filePartNames) {
        VolleyUtils.requestServiceWithFile(SystemConst.SAVE_FILE, URL.getModifyPhotoParams(getLoginUserId()), filePartNames, files,

                new LoadingDialogResultListenerImpl(this, "正在提交数据") {
                    @Override
                    public void onSuccess(String response) {
                        super.onSuccess(response);
                        ResultVo<?> vo = GsonUtil.deser(response, ResultVo.class);
                        if (vo == null) {
                            return;
                        }
                        if (vo.getResult() == 1) {
                            doToast("添加成功");
                            Intent intent = new Intent();
                            intent.putExtra("success", true);
                            setResult(RESULT_OK, intent);
                            AppManager.getAppManager().finishActivity(ActAddFileDetail.class);
                        } else {
                            doToast(vo.getMsg());
                        }
                    }

                    @Override
                    public void onError() {
                        super.onError();
                    }
                });
    }

    // 处理图片剪切的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CropHelper.handleResult(mCropHandler,requestCode,resultCode,data);
    }

//    private void selectHeadImg() {
//        ActionSheetDialog photoDialog = new ActionSheetDialog(this);
//        photoDialog.builder();
//        photoDialog.setCancelable(true);
//        photoDialog.setCanceledOnTouchOutside(true);
//        photoDialog.addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {
//            @Override
//            public void onClick(int which) {
//                takeCapture();
//            }
//
//        });
//        photoDialog.addSheetItem("从相册中选择", ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {
//
//            @Override
//            public void onClick(int which) {
//                fromLocal();
//            }
//
//        });
//        photoDialog.show();
//    }


    private String filePath;

    /**
     * 拍照
     */
    private void takeCapture() {
        filePath = ImageUtil.getPicture(this);
    }


    /**
     * 本地选取
     */
    private void fromLocal() {

        ImageUtil.fromLocal(this);
    }


    private void getMemberDetail() {
        VolleyUtils.requestService(SystemConst.MEMBER_DETAIL_URL, URL.getMemberDetail(getLoginUserId()), new ResultListenerImpl(this) {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                if (TextUtils.isEmpty(response)) {
                    return;
                }
                MemberVo vo = GsonUtil.deser(response, MemberVo.class);
                if (vo == null) {
                    return;
                }
                if (vo.getResult() == 1) {
                    if (vo.getList() != null && vo.getList().size() > 0) {
                        SystemEnv.saveUser(vo.getList().get(0));
                        App.getInstance().login(vo.getList().get(0));
                        refreshUI();
                    }
                } else {
                    doToast(vo.getMsg());
                }
            }

            @Override
            public void onError() {
                super.onError();
            }
        });
    }

    public void onPause() {
        super.onPause();
    }

    class MemberVo extends ResultVo<User> {

    }

    /**
     * 刷新ui
     */
    private void refreshUI() {
        if (!TextUtils.isEmpty(getLoginUserId())) {
            ivNotLogin.setVisibility(View.GONE);
            txtName.setText(getUnNullString(getLoginUser().getLoginName(), ""));


        } else {
            scrollView.smoothScrollTo(0, 1);
            ivNotLogin.setVisibility(View.VISIBLE);

        }
    }
    @Override
    protected void onDestroy() {
        if (mCropHandler.getCropParams() != null)
            CropHelper.clearCachedCropFile(mCropHandler.getCropParams().uri);
        super.onDestroy();
    }
}
